﻿using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Threading.Tasks;

namespace Canteen.Core.Common
{
    //验证“跨站点请求伪造 (XSRF/CSRF) 攻击”的请求内容 --Authorization过滤器
    public class ValidateAntiforgeryAuthorizationFilter : IAsyncAuthorizationFilter
    {
        private readonly IAntiforgery _antiforgery;

        public ValidateAntiforgeryAuthorizationFilter(IAntiforgery antiforgery)
        {
            _antiforgery = antiforgery ?? throw new ArgumentNullException(nameof(antiforgery));
        }

        public async Task OnAuthorizationAsync(AuthorizationFilterContext context)
        {
            if (context == null) throw new ArgumentNullException(nameof(context));
            try
            {
                await _antiforgery.ValidateRequestAsync(context.HttpContext);
            }
            catch (AntiforgeryValidationException)
            {
                var tokens = _antiforgery.GetAndStoreTokens(context.HttpContext);//生成新的token
                context.HttpContext.Response.Headers[tokens.HeaderName] = tokens.RequestToken;//添加到响应头中

                context.Result = new ObjectResult("验证防伪凭证失败")
                {
                    StatusCode = StatusCodes.Status412PreconditionFailed
                };
            }
        }
    }
}